package com.druid.controller;

import com.druid.common.ConstantCache;
import com.druid.entity.CeSecurityRole;
import com.druid.model.PageBody;
import com.druid.model.ResponseData;
import com.druid.request.PageParam;
import com.druid.request.RequestParamInterfaceGroup;
import com.druid.request.SecutityRoleParam;
import com.druid.response.CeSecurityRoleVm;
import com.druid.service.managementservice.ICeSecurityRoleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.util.List;

/**
 * @author druid-elf
 * @since 2019-12-25
 */
@Api(tags={"角色表前端控制器"})
@RestController
@RequestMapping("/ceSecurityRole")
@RequiredArgsConstructor
public class CeSecurityRoleController {

    private final ICeSecurityRoleService iCeSecurityRoleService;

    @ApiOperation("得到角色表分页列表")
    @PostMapping(value = "getCeSecurityRolePageList")
    public ResponseData<PageBody<CeSecurityRoleVm>> getCeSecurityRolePageList(@RequestBody @Validated PageParam pageParam ) {

        return ResponseData.SUCCESS(
                iCeSecurityRoleService.getCeSecurityRolePageList(pageParam)
        );
    }

    @ApiOperation("得到所有角色信息")
    @GetMapping("getCeSecurityRoleList")
    public ResponseData<List<CeSecurityRole>> getCeSecurityRoleList() {

        return ResponseData.SUCCESS(
                ConstantCache.getSecurityRoleListCache()
        );
    }

    @ApiOperation("根据主键id删除角色")
    @PostMapping(value = "deleteSecurityRole")
    public ResponseData<String> deleteSecurityRole (@RequestBody @Validated(RequestParamInterfaceGroup.DeleteGroup.class) SecutityRoleParam secutityRoleParam) {

        return iCeSecurityRoleService.removeById( secutityRoleParam.getId() )
                ? ResponseData.SUCCESS("操作成功")
                : ResponseData.FAILURE("操作失败");
    }

    @ApiOperation("保存角色")
    @PostMapping(value = "saveOrUpdateSecurityRole")
    public ResponseData<String> saveOrUpdateSecurityRole (@RequestBody @Validated(RequestParamInterfaceGroup.InsertGroup.class) SecutityRoleParam secutityRoleParam) {

        if ( secutityRoleParam.getRoleId() == null ) {
            Integer maxRoleId = iCeSecurityRoleService.list().stream().map(CeSecurityRole::getRoleId).max(Integer::compareTo).orElse(0);
            secutityRoleParam.setRoleId(maxRoleId+1);
        }
        return iCeSecurityRoleService.saveOrUpdate(CeSecurityRole.builder().name(secutityRoleParam.getName()).roleId(secutityRoleParam.getRoleId()).build())
                ? ResponseData.SUCCESS("操作成功")
                : ResponseData.FAILURE("操作失败");
    }
}
